package com.coupon.constrol;

import com.coupon.util.JsonResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @author :wn
 * @program : coupon
 * @descript :
 * @create :2021-01-05 09:42
 */
@Controller
@RequestMapping("/cpn")
public class UploadController {
    @RequestMapping("/upload")
    @ResponseBody
    public Map upload(@RequestParam("file")MultipartFile multipartFile,HttpSession session) throws IOException {
        long size = multipartFile.getSize();
        if(size>(1024*1024)){
            JsonResult jsonResult=new JsonResult();
            return jsonResult.getValues();
        }else {

            String originalFilename = multipartFile.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uuid = UUID.randomUUID().toString();
            String replace = uuid.replace("-", "");
            ServletContext servletContext = session.getServletContext();
            String realPath = servletContext.getRealPath("/");
            System.out.println(realPath);
            String pathName = realPath + "static\\images\\" + replace+substring;
            String imagesName=replace+substring;
            System.out.println(pathName);
            File targetFile = new File(pathName);
            multipartFile.transferTo(targetFile);
            JsonResult jsonResult=new JsonResult();
            jsonResult.put("fileName",imagesName);
            jsonResult.setCode(1);
            return jsonResult.getValues();
        }


    }
}
